package loading;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.Timer;

import model.LogList;
import model.loading.FileLoader;

/**
 * This class can control a FileLoader, forcing it to load informations when the
 * file the loader is working on changes.
 * 
 * @author simone
 *
 */
public class FileChecker {

	private Timer timer;
	private ToBeEdited list;
	private FileLoader loader;
	private long lastModified;

	/**
	 * Create a new istance of this class
	 * 
	 * @param delay
	 *            : the check delay
	 * @param list
	 *            : the list to reset when reloaded
	 * @param loader
	 *            : the loader to control
	 */
	public FileChecker(int delay, ToBeEdited list, FileLoader loader) {
		super();
		this.timer = new Timer(delay, new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					check();
				} catch (IOException e1) {
				}
			}
		});
		timer.start();
		this.list = list;
		this.loader = loader;
	}

	private void check() throws IOException {
		long check = loader.getFile().lastModified();
		if (check > this.lastModified) {
			this.lastModified = check;
			this.list.clear();
			this.loader.loadFile();
		}
	}
}
